package com.fengkai.filepost.pdfoutstream.test.ODsolutions;


import java.util.Arrays;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Fengkai
 * @creat 2023/4/12
 * 相对开音节构成的结构为辅音+元音（aeiou）+辅音(r 除外)+e，常见的单词有 bike、cake 等。
 * 给定一个字符串，以空格为分隔符，反转每个单词中的字母，若单词中包含如数字等其他非字母时不进行反转。
 * 反转后计算其中含有相对开音节结构的子串个数（连续的子串中部分字符可以重复）。
 * 输入描述:
 * 字符串，以空格分割的多个单词，字符串长度<10000，字母只考虑小写
 * 输出描述:
 * 含有相对开音节结构的子串个数，注：个数<10000
 */
public class KaiYInJie {

    public static void main (String[] args) {
        System.out.println(getKaiYinJieCount("!ekam a ekekac"));

    }

    public static int getKaiYinJieCount (String input) {
        String[] strings = input.split(" ");
        String[] toCount = practiesString(strings);
        int result = 0;
        for (int i = 0; i < toCount.length; i++) {
            result += toCount(toCount[i]);
        }
        return result;
    }

    private static int toCount (String toCount) {
        int left = 0;
        int right = left + 3;
        int count = 0;
        Pattern compile = Pattern.compile("[^a-zA-Z0-9]+");
        while (left < toCount.length() && right < toCount.length()) {
            if (compile.matcher(toCount.substring(left, right + 1)).find()){
                left ++;
                right ++;
                continue;
            }
            if (toCount.charAt(right) != 'e'){
                left ++;
                right ++;
                continue;
            }
            if (toCount.substring(left, left + 1).matches("[aeiou]")){
                left ++;
                right ++;
                continue;
            }
            if (!toCount.substring(left +1, left + 2).matches("[aeiou]")){
                left ++;
                right ++;
                continue;
            }
            if (toCount.substring(left + 2, right).matches("[aeiour]")){
                left ++;
                right ++;
                continue;
            }
            left ++;
            right ++;
            count ++;
        }
        return count;
    }

    private static String[] practiesString (String[] input) {
        Stack<Character> characters = new Stack<>();
        String[] toCount = new String[input.length];
        Pattern compile = Pattern.compile("[^a-zA-Z]+");
        for (int i = 0; i < input.length; i++) {
            //匹配到非字母就不翻转
            Matcher matcher = compile.matcher(input[i]);
            if (matcher.find()) {
                toCount[i] = input[i];
            } else {
                for (int j = 0; j < input[i].length(); j++) {
                    characters.push(input[i].charAt(j));
                }
                String cahce = "";
                while (!characters.isEmpty()) {
                    cahce += characters.pop();
                }
                toCount[i] = cahce;
            }
        }
        return toCount;
    }
}
